using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public Ball ball;
    public List<GameObject> players;

    [SerializeField] private Transform ballSpawn;
    [SerializeField] private List<Transform> playerSpawns;
    [SerializeField] private int goalsToWin;

    [Header("UI")]
    [SerializeField] private TextMeshProUGUI scoreText;
    [SerializeField] private Slider staminaBar;
    [SerializeField] private PlayerMovement player;

    // score[0] is Team 1's score and score[1] is Team 2's score
    public static int[] score;

    #region Singleton Declaration
    public static GameManager instance;

    private void Awake()
    {
        if(instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(this);
        }
    }
    #endregion

    private void Start()
    {
        score = new int[2];
        ResetLevel();
    }

    private void Update()
    {
        if (staminaBar != null) staminaBar.value = player.stamina;
    }

    public void TeamScored(int team)
    {
        score[team]++;
        scoreText.text = score[0] + " - " + score[1];

        if (score[team] >= goalsToWin)
        {
            SceneManager.LoadScene(5);
        }

        ResetLevel();
    }

    public void ResetLevel()
    {
        ball.gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
        ball.transform.position = ballSpawn.position;
        
        for(int i = 0; i < players.Count; i++)
        {
            players[i].transform.position = playerSpawns[i].position;
            players[i].GetComponent<Rigidbody>().velocity = Vector3.zero;
        }
    }
}
